package v1

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"supervideo/app/models/video"
	"supervideo/app/models/video_category_map"
	"supervideo/pkg/database"
	"supervideo/pkg/response"
)

type VideoController struct {
	BaseAPIController
}

func (videoCtr VideoController) Videos(c *gin.Context) {

	zoneId, _ := strconv.Atoi(c.Query("zone_id"))
	categoryId, _ := strconv.Atoi(c.Query("cat"))
	addressId, _ := strconv.Atoi(c.Query("addr"))
	sortId, _ := strconv.Atoi(c.Query("so"))
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("page_size"))

	query := database.DB.Model(&video.Video{}).Where("zone_id = ?", zoneId).Where("status = ?", 1)

	var videos []video.Video

	if categoryId != 0 {
		// 搜索出对应的存放的ID
		var ids []string
		database.DB.Model(video_category_map.VideoCategoryMap{}).Where("category_id", categoryId).Pluck("video_id", &ids)
		query = query.Where("id in ?", ids)
	}
	if addressId != 0 {
		query = query.Where("address_id = ?", addressId)
	}
	if sortId == 1 {
		query = query.Order("created_at desc")
	}
	if sortId == 2 {
		query = query.Order("sort desc")
	}
	if sortId == 3 {
		query = query.Order("grade desc")
	}
	if page > 0 && pageSize > 0 {
		query = query.Limit(pageSize).Offset((page - 1) * pageSize)
	}

	query.Find(&videos)
	response.Data(c, videos)
}
